import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import * as enterpriseApi from '@/apis/enterprise';

/**
 * 企业管理相关的Hook
 */
export function useEnterpriseManagement() {
  // 状态管理
  const loading = ref(false);
  const enterpriseData = ref([]);
  
  // 分页数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });
  
  // 搜索条件
  const searchParams = reactive({
    name: '',
    contactName: '',
    address: '',
    status: ''
  });

  /**
   * 获取企业列表数据
   */
  const fetchEnterpriseData = async () => {
    loading.value = true;
    
    try {
      const params = {
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize,
        name: searchParams.name,
        contactName: searchParams.contactName,
        address: searchParams.address,
        status: searchParams.status !== '' ? parseInt(searchParams.status) : null
      };
      
      const response = await enterpriseApi.getEnterpriseList(params);
      // 确保数据格式匹配，将后端返回的数字状态转换为字符串
      enterpriseData.value = response.data.records.map(item => ({
        ...item,
        status: String(item.status)
      }));
      pagination.total = response.data.total;
      console.log('获取企业数据成功:', response.data);
      
    } catch (error) {
      ElMessage.error('获取企业数据失败');
      console.error('获取企业数据错误:', error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 搜索企业
   */
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchEnterpriseData();
  };

  /**
   * 重置搜索条件
   */
  const handleReset = () => {
    Object.assign(searchParams, {
      name: '',
      contactName: '',
      address: '',
      status: ''
    });
    pagination.currentPage = 1;
    fetchEnterpriseData();
  };

  /**
   * 分页大小变化
   */
  const handleSizeChange = (size) => {
    pagination.pageSize = size;
    fetchEnterpriseData();
  };

  /**
   * 页码变化
   */
  const handleCurrentChange = (current) => {
    pagination.currentPage = current;
    fetchEnterpriseData();
  };

  /**
   * 添加企业
   */
  const addEnterprise = async (data) => {
    try {
      // 确保状态值为数字类型
      const enterpriseData = {
        ...data,
        status: data.status ? parseInt(data.status) : 0 // 默认待审核状态
      };
      await enterpriseApi.addEnterprise(enterpriseData);
      ElMessage.success('企业添加成功');
      fetchEnterpriseData();
    } catch (error) {
      ElMessage.error('添加企业失败');
      console.error('添加企业错误:', error);
      throw error;
    }
  };

  /**
   * 更新企业
   */
  const updateEnterprise = async (id, data) => {
    try {
      // 确保状态值为数字类型
      const enterpriseData = {
        ...data,
        status: data.status ? parseInt(data.status) : undefined
      };
      await enterpriseApi.updateEnterprise(id, enterpriseData);
      ElMessage.success('企业更新成功');
      fetchEnterpriseData();
    } catch (error) {
      ElMessage.error('更新企业失败');
      console.error('更新企业错误:', error);
      throw error;
    }
  };

  /**
   * 删除企业
   */
  const deleteEnterprise = async (id) => {
    try {
      await enterpriseApi.deleteEnterprise(id);
      ElMessage.success('企业删除成功');
      fetchEnterpriseData();
    } catch (error) {
      ElMessage.error('删除企业失败');
      console.error('删除企业错误:', error);
      throw error;
    }
  };

  /**
   * 审核企业
   */
  const auditEnterprise = async (id, status, reason) => {
    try {
      // 构建审核参数
      const params = {
        status: parseInt(status)
      };
      
      if (status === 2 && reason) {
        params.reason = reason;
      }
      
      // 调用审核API
      await enterpriseApi.auditEnterprise(id, params);
      ElMessage.success('审核操作成功');
      fetchEnterpriseData();
    } catch (error) {
      ElMessage.error('审核操作失败');
      console.error('审核企业错误:', error);
      throw error;
    }
  };

  /**
   * 获取企业状态文本
   */
  const getStatusText = (status) => {
    const statusMap = {
      '0': '待审核',
      '1': '正常',
      '2': '审核失败',
      '3': '禁用'
    };
    return statusMap[status] || '未知';
  };

  /**
   * 获取企业状态标签类型
   */
  const getStatusTagType = (status) => {
    const typeMap = {
      '0': 'warning',
      '1': 'success',
      '2': 'danger',
      '3': 'info'
    };
    return typeMap[status] || 'default';
  };

  return {
    loading,
    enterpriseData,
    pagination,
    searchParams,
    fetchEnterpriseData,
    handleSearch,
    handleReset,
    handleSizeChange,
    handleCurrentChange,
    addEnterprise,
    updateEnterprise,
    deleteEnterprise,
    auditEnterprise,
    getStatusText,
    getStatusTagType
  };
}

// 添加默认导出，兼容不同的导入方式
export default useEnterpriseManagement;